﻿<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.Common" %>
<%@ Import Namespace="Microsoft.Practices.EnterpriseLibrary.Data" %>
<%@ Import Namespace="Hidistro.Core" %>
<%@ Import Namespace="Hidistro.UI.SaleSystem.CodeBehind" %>
<%@ Import Namespace="System.Reflection" %>
<%@ Import Namespace="wnxd.javascript" %>
<script runat="server">
    protected override void OnInit(EventArgs e)
    {
        string id = this.Request.Form["id"];
        if (!string.IsNullOrEmpty(id) && this.Validate(id))
        {
            json ret = new json(new { status = main() });
            this.Response.Write(ret.ToString());
        }
        else
        {
            this.Response.Redirect("~/errorinfo.htm");
        }
    }
    private bool main()
    {
        switch (this.Request.Form["a"])
        {
            case "g": return generate();
            case "d": return delete();
            case "q": return query();
            case "s": return stop();
            case "t": return template();
        }
        return false;
    }
    private bool generate()
    {
        switch (this.Request.Form["b"])
        {
            case "p": return generate_product();
            case "c": return generate_category();
            case "gc": return generate_common();
        }
        return false;
    }
    private bool delete()
    {
        switch (this.Request.Form["b"])
        {
            case "p": return delete_product();
            case "c": return delete_category();
        }
        return false;
    }
    private bool query()
    {
        switch (this.Request.Form["b"])
        {
            case "p": return query_product();
            case "c": return query_category();
        }
        return false;
    }
    private bool stop()
    {
        switch (this.Request.Form["b"])
        {
            case "p": return stop_product();
            case "c": return stop_category();
        }
        return false;
    }
    private bool generate_product()
    {
        string wpath = this.MapPathSecure("~/wnxd/");
        if (!Directory.Exists(wpath)) Directory.CreateDirectory(wpath);
        string status = this._ReadFile(wpath + "wnxd_generate_product.tmp");
        if (!string.IsNullOrEmpty(status) && status != "ok" && status != "fail") return false;
        string ProductId = this.Request.Form["c"];
        int i = 0;
        string pdstr = "";
        Action<string, string> func = (fenlei, pid) =>
        {
            HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(this.Page.Request.Url.Scheme + "://" + this.Page.Request.Url.Authority + "/ProductDetails.aspx?productId=" + pid);
            pdstr=Request.Address.ToString();
            Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2427.7 Safari/537.36";
            using (WebResponse Response = Request.GetResponse())
            using (Stream resStream = Response.GetResponseStream())
            using (StreamReader sr = new StreamReader(resStream, Encoding.UTF8))
            {
                string path = this.MapPath("~/" + fenlei);
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                File.WriteAllText(this.MapPath("~" + Globals.GetSiteUrls().UrlData.FormatUrl("productDetails", new object[] { pid, fenlei })), sr.ReadToEnd());
            }
            this._WriteFile(wpath + "wnxd_generate_product.tmp", (++i).ToString());
        };
        try
        {
           
            this._WriteFile(wpath + "wnxd_generate_product.tmp", "0");
            if (string.IsNullOrEmpty(ProductId))
            {
                DataTable dt = this.sql_call("select t1.ProductId,t3.RewriteName from Hishop_Products t1 left join Hishop_Categories t2 on t2.CategoryId = t1.CategoryId left join Hishop_Categories t3 on t3.CategoryId = t2.ParentCategoryId where SaleStatus = 1");
                this._WriteFile(wpath + "wnxd_product_num.tmp", dt.Rows.Count.ToString());
                foreach (DataRow row in dt.Rows)
                {
                    ProductId = row["ProductId"].ToString();
                    func(row["RewriteName"].ToString(), ProductId);
                }
            }
            else
            {
                string RewriteName = this.sql_run("select t3.RewriteName from Hishop_Products t1 left join Hishop_Categories t2 on t2.CategoryId = t1.CategoryId left join Hishop_Categories t3 on t3.CategoryId = t2.ParentCategoryId where SaleStatus = 1 and ProductId = " + ProductId).ToString();
                func(RewriteName, ProductId);
            }
        }
        catch (Exception ex)
        {
            string aa = pdstr;
            this._WriteFile(wpath + "wnxd_generate_product.tmp", aa);
            StringBuilder str = new StringBuilder();
            str.AppendLine("----------------商品生成--------------------------------------------------------------------------");
            str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
            str.AppendLine("客户信息：");
            string ip = "";
            if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
            {
                ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
            }
            else
            {
                ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
            }
            str.AppendLine("连接IP:" + Request.UserHostAddress);
            str.AppendLine("IP:" + ip);
            str.AppendLine("连接主机名:" + Request.UserHostName);
            str.AppendLine("浏览器:" + Request.Browser.Browser);
            str.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());
            str.AppendLine("操作系统:" + Request.Browser.Platform);
            str.AppendLine("错误信息:");
            str.AppendLine("页面：" + Request.Url.ToString());
            str.AppendLine("错误信息：" + ex.Message);
            str.AppendLine("错误源：" + ex.Source);
            str.AppendLine("异常方法：" + ex.TargetSite);
            str.AppendLine("堆栈信息：" + ex.StackTrace);
            str.AppendLine("--------------------------------------------------------------------------------------------------");
            string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            string FileName;
            string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
            if (flist != null && flist.Length > 0)
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                FileInfo fileInfo = new FileInfo(FileName);
                if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                }
            }
            else
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
            }
            File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
            return false;
        }
        this._WriteFile(wpath + "wnxd_generate_product.tmp", "ok");;
        return true;
    }
    private bool generate_category()
    {
        string wpath = this.MapPathSecure("~/wnxd/");
        if (!Directory.Exists(wpath)) Directory.CreateDirectory(wpath);
        string status = this._ReadFile(wpath + "wnxd_generate_category.tmp");
        if (!string.IsNullOrEmpty(status) && status != "ok" && status != "fail") return false;
        string CategoryId = this.Request.Form["c"];
        Type T = typeof(HttpRequest);
        FieldInfo _url = T.GetField("_url", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        FieldInfo _rawUrl = T.GetField("_rawUrl", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        object old_url = _url.GetValue(this.Page.Request);
        object old_RawUrl = _rawUrl.GetValue(this.Page.Request);
        int i = 0;
        Action<string, string> func = (fenlei, cid) =>
        {
            using (TextWriter tw = new StringWriter())
            {
                _url.SetValue(this.Page.Request, new Uri(this.Page.Request.Url.Scheme + "://" + this.Page.Request.Url.Authority + "/SubPage_new.aspx?CategoryId=" + cid));
                _rawUrl.SetValue(this.Page.Request, Globals.GetSiteUrls().UrlData.FormatUrl("subCategory_Rewrite", new object[] { fenlei }));
                this.Server.Execute("/SubPage_new.aspx?CategoryId=" + cid, tw, false);
                string path = this.MapPath("~/" + fenlei);
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                File.WriteAllText(this.MapPath("~" + this.Page.Request.RawUrl + "index.html"), tw.ToString());
                this._WriteFile(wpath + "wnxd_generate_category.tmp", (++i).ToString());
            }
        };
        try
        {
            this._WriteFile(wpath + "wnxd_generate_category.tmp", "0");
            if (string.IsNullOrEmpty(CategoryId))
            {
                DataTable dt = this.sql_call("select CategoryId,RewriteName from Hishop_Categories where ParentCategoryId = 0 and Depth = 1");
                this._WriteFile(wpath + "wnxd_category_num.tmp", dt.Rows.Count.ToString());
                foreach (DataRow row in dt.Rows)
                {
                    CategoryId = row["CategoryId"].ToString();
                    func(row["RewriteName"].ToString(), CategoryId);
                }
            }
            else
            {
                string RewriteName = this.sql_run("select RewriteName from Hishop_Categories where ParentCategoryId = 0 and Depth = 1 and CategoryId = " + CategoryId).ToString();
                func(RewriteName, CategoryId);
            }
        }
        catch (Exception ex)
        {
            this._WriteFile(wpath + "wnxd_generate_category.tmp", "fail");
            StringBuilder str = new StringBuilder();
            str.AppendLine("----------------分类生成--------------------------------------------------------------------------");
            str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
            str.AppendLine("客户信息：");
            string ip = "";
            if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
            {
                ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
            }
            else
            {
                ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
            }
            str.AppendLine("连接IP:" + Request.UserHostAddress);
            str.AppendLine("IP:" + ip);
            str.AppendLine("连接主机名:" + Request.UserHostName);
            str.AppendLine("浏览器:" + Request.Browser.Browser);
            str.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());
            str.AppendLine("操作系统:" + Request.Browser.Platform);
            str.AppendLine("错误信息:");
            str.AppendLine("页面：" + Request.Url.ToString());
            str.AppendLine("错误信息：" + ex.Message);
            str.AppendLine("错误源：" + ex.Source);
            str.AppendLine("异常方法：" + ex.TargetSite);
            str.AppendLine("堆栈信息：" + ex.StackTrace);
            str.AppendLine("--------------------------------------------------------------------------------------------------");
            string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            string FileName;
            string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
            if (flist != null && flist.Length > 0)
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                FileInfo fileInfo = new FileInfo(FileName);
                if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                }
            }
            else
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
            }
            File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
            _url.SetValue(this.Page.Request, old_url);
            _rawUrl.SetValue(this.Page.Request, old_RawUrl);
            return false;
        }
        this._WriteFile(wpath + "wnxd_generate_category.tmp", "ok");
        _url.SetValue(this.Page.Request, old_url);
        _rawUrl.SetValue(this.Page.Request, old_RawUrl);
        return true;
    }
    private bool generate_common()
    {
        string url = HttpUtility.UrlDecode(this.Request.Form["c"]);
        if (string.IsNullOrWhiteSpace(url)) return false;
        try
        {
            Type T = typeof(HttpRequest);
            FieldInfo _url = T.GetField("_url", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            FieldInfo _rawUrl = T.GetField("_rawUrl", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (url.First() != '/') url = "/" + url;
            using (TextWriter tw = new StringWriter())
            {
                _url.SetValue(this.Page.Request, new Uri(url));
                _rawUrl.SetValue(this.Page.Request, url);
                this.Server.Execute(url, tw, true);
                string path = this.MapPath("~" + url);
                this._WriteFile(Path.GetDirectoryName(path) + "/" + Path.GetFileNameWithoutExtension(path) + ".html", tw.ToString());
            }
        }
        catch (Exception ex)
        {
            StringBuilder str = new StringBuilder();
            str.AppendLine("----------------分类生成--------------------------------------------------------------------------");
            str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
            str.AppendLine("客户信息：");
            string ip = "";
            if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
            {
                ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
            }
            else
            {
                ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
            }
            str.AppendLine("连接IP:" + Request.UserHostAddress);
            str.AppendLine("IP:" + ip);
            str.AppendLine("连接主机名:" + Request.UserHostName);
            str.AppendLine("浏览器:" + Request.Browser.Browser);
            str.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());
            str.AppendLine("操作系统:" + Request.Browser.Platform);
            str.AppendLine("错误信息:");
            str.AppendLine("页面：" + Request.Url.ToString());
            str.AppendLine("错误信息：" + ex.Message);
            str.AppendLine("错误源：" + ex.Source);
            str.AppendLine("异常方法：" + ex.TargetSite);
            str.AppendLine("堆栈信息：" + ex.StackTrace);
            str.AppendLine("--------------------------------------------------------------------------------------------------");
            string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            string FileName;
            string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
            if (flist != null && flist.Length > 0)
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                FileInfo fileInfo = new FileInfo(FileName);
                if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                }
            }
            else
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
            }
            File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
            return false;
        }
        return true;
    }
    private bool delete_product()
    {
        string ProductId = this.Request.Form["c"];
        if (!string.IsNullOrEmpty(ProductId))
        {
            try
            {
                string RewriteName = this.sql_run("select t3.RewriteName from Hishop_Products t1 left join Hishop_Categories t2 on t2.CategoryId = t1.CategoryId left join Hishop_Categories t3 on t3.CategoryId = t2.ParentCategoryId where SaleStatus = 1 and ProductId = " + ProductId).ToString();
                File.Delete(this.MapPath("~" + Globals.GetSiteUrls().UrlData.FormatUrl("productDetails", new object[] { ProductId, RewriteName })));
                return true;
            }
            catch
            {

            }
        }
        return false;
    }
    private bool delete_category()
    {
        string CategoryId = this.Request.Form["c"];
        if (!string.IsNullOrEmpty(CategoryId))
        {
            try
            {
                string RewriteName = this.sql_run("select RewriteName from Hishop_Categories where ParentCategoryId = 0 and Depth = 1 and CategoryId = " + CategoryId).ToString();
                File.Delete(this.MapPath("~" + Globals.GetSiteUrls().UrlData.FormatUrl("subCategory_Rewrite", new object[] { RewriteName }) + "index.html"));
                return true;
            }
            catch
            {

            }
        }
        return false;
    }
    private bool query_product()
    {
        string wpath = this.MapPathSecure("~/wnxd/");
        string status = this._ReadFile(wpath + "wnxd_generate_product.tmp");
        this.Response.Write(new json(new { status = true, data = new { now = status, total = this._ReadFile(wpath + "wnxd_product_num.tmp") } }).ToString());
        this.Response.End();
        return false;
    }
    private bool query_category()
    {
        string wpath = this.MapPathSecure("~/wnxd/");
        string status = this._ReadFile(wpath + "wnxd_generate_category.tmp");
        this.Response.Write(new json(new { status = true, data = new { now = status, total = this._ReadFile(wpath + "wnxd_category_num.tmp") } }).ToString());
        this.Response.End();
        return false;
    }
    private bool stop_product()
    {
        try
        {
            File.Delete(this.MapPathSecure("~/wnxd/wnxd_generate_product.tmp"));
            return true;
        }
        catch
        {
            return false;
        }
    }
    private bool stop_category()
    {
        try
        {
            File.Delete(this.MapPathSecure("~/wnxd/wnxd_generate_category.tmp"));
            return true;
        }
        catch
        {
            return false;
        }
    }
    private bool template()
    {
        string domain = HttpUtility.UrlDecode(this.Request.Form["b"]);
        if (string.IsNullOrWhiteSpace(domain)) return this.generate_common();
        string url = HttpUtility.UrlDecode(this.Request.Form["c"]);
        if (string.IsNullOrWhiteSpace(url)) return false;
        try
        {
            if (domain.Last() != '/') domain += "/";
            if (url.First() == '/') url = url.Substring(1);
            HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(domain + url);
            Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2427.7 Safari/537.36";
            using (WebResponse Response = Request.GetResponse())
            using (Stream resStream = Response.GetResponseStream())
            using (StreamReader sr = new StreamReader(resStream, Encoding.UTF8))
            {
                string path = this.MapPath("~/" + url);
                this._WriteFile(Path.GetDirectoryName(path) + "/" + Path.GetFileNameWithoutExtension(path) + ".html", sr.ReadToEnd());
            }
        }
        catch (Exception ex)
        {
            StringBuilder str = new StringBuilder();
            str.AppendLine("----------------分类生成--------------------------------------------------------------------------");
            str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
            str.AppendLine("客户信息：");
            string ip = "";
            if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
            {
                ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
            }
            else
            {
                ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
            }
            str.AppendLine("连接IP:" + Request.UserHostAddress);
            str.AppendLine("IP:" + ip);
            str.AppendLine("连接主机名:" + Request.UserHostName);
            str.AppendLine("浏览器:" + Request.Browser.Browser);
            str.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());
            str.AppendLine("操作系统:" + Request.Browser.Platform);
            str.AppendLine("错误信息:");
            str.AppendLine("页面：" + Request.Url.ToString());
            str.AppendLine("错误信息：" + ex.Message);
            str.AppendLine("错误源：" + ex.Source);
            str.AppendLine("异常方法：" + ex.TargetSite);
            str.AppendLine("堆栈信息：" + ex.StackTrace);
            str.AppendLine("--------------------------------------------------------------------------------------------------");
            string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            string FileName;
            string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
            if (flist != null && flist.Length > 0)
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                FileInfo fileInfo = new FileInfo(FileName);
                if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                }
            }
            else
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
            }
            File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
            return false;
        }
        return true;
    }


    private void _OnInit(Control control)
    {
        Type T = control.GetType();
        MethodInfo mi = T.GetMethod("OnInit", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        if (mi != null) mi.Invoke(control, new object[] { new EventArgs() });
        for (int i = 0; i < control.Controls.Count; i++) this._OnInit(control.Controls[i]);
    }
    private void _EnsureChildControls(Control control)
    {
        Type T = control.GetType();
        MethodInfo mi = T.GetMethod("EnsureChildControls", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        if (mi != null) mi.Invoke(control, null);
        for (int i = 0; i < control.Controls.Count; i++) this._EnsureChildControls(control.Controls[i]);
    }
    private bool Validate(string guid)
    {
        using (DbCommand cmd = database.GetSqlStringCommand("select count(*) from wnxd_Validate where GUID = '" + guid + "'"))
        {
            int count = (int)database.ExecuteScalar(cmd);
            bool ret = count > 0;
            if (ret) using (DbCommand sql = database.GetSqlStringCommand("delete from wnxd_Validate where GUID = '" + guid + "'")) ret = database.ExecuteNonQuery(sql) == 1;
            return ret;
        }
    }
    private Database database = DatabaseFactory.CreateDatabase();
    private DataTable sql_call(string sql)
    {
        using (DbCommand cmd = database.GetSqlStringCommand(sql))
        using (IDataReader reader = database.ExecuteReader(cmd))
        {
            return DataHelper.ConverDataReaderToDataTable(reader);
        }
    }
    private object sql_run(string sql)
    {
        using (DbCommand cmd = database.GetSqlStringCommand(sql)) return database.ExecuteScalar(cmd);
    }
    private string _ReadFile(string path)
    {
        string res;
        try
        {
            if (!File.Exists(path)) return null;
            using (FileStream fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
            using (StreamReader sr = new StreamReader(fs))
            {
                res = sr.ReadToEnd();
            }
        }
        catch
        {
            res = _ReadFile(path);
        }
        return res;
    }
    private void _WriteFile(string path, string contents)
    {
        try
        {
            using (FileStream fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read))
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.Write(contents);
                sw.Flush();
            }
        }
        catch
        {
            _WriteFile(path, contents);
        }
    }
</script>
